package com.doupi.partner.util;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * spring context utils
 * 
 * @author Super Jens Wang
 *
 * @version 1.0 @ 2016年7月20日 上午5:21:06
 */
public class SpringContextUtils implements ApplicationContextAware {
	private final static Logger LOGGER = LoggerFactory.getLogger(SpringContextUtils.class);
	private static ApplicationContext APPLICATION_CONTEXT = null;

	/**
	 * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
	 */
	public void setApplicationContext(ApplicationContext applicationContext) {
		LOGGER.warn("当前的激活的环境：" + Arrays.deepToString(applicationContext.getEnvironment().getActiveProfiles()));
		LOGGER.warn("当前的默认的环境：" + Arrays.deepToString(applicationContext.getEnvironment().getDefaultProfiles()));
		SpringContextUtils.APPLICATION_CONTEXT = applicationContext;
	}

	/**
	 * 获取ApplicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return APPLICATION_CONTEXT;
	}

	/**
	 * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBeanByName(String name) {
		return (T) APPLICATION_CONTEXT.getBean(name);
	}

	/**
	 * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBeanByClass(Class<T> clazz) {
		return APPLICATION_CONTEXT.getBean(clazz);
	}

}
